import 'dart:math';

import 'package:flutter/material.dart';

/**
 * key
 * StatelessWidget 的 color属于widget
 * StatefulWidget 的color 属于 State
 *
 * key本身是个抽象类，有一个工厂
 *
 */
class KeyDemo extends StatefulWidget {
  const KeyDemo({super.key});

  @override
  State<KeyDemo> createState() => _KeyDemoState();
}

class _KeyDemoState extends State<KeyDemo> {
  ///未加key 删除颜色从后往前（有问题）
  // List<Widget> items = [
  //   StfulItem(title: '111'),
  //   StfulItem(title: '222'),
  //   StfulItem(title: '333')
  // ];

  List<Widget> items = [
    StfulItem(
      title: '111',
      key: const ValueKey(1),
    ),
    StfulItem(
      title: '222',
      key: const ValueKey(2),
    ),
    StfulItem(
      title: '333',
      key: const ValueKey(3),
    )
  ];

  ///stless 无问题
  // List<Widget> items = [
  //   StlItem(title: '111'),
  //   StlItem(title: '222'),
  //   StlItem(title: '333')
  // ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Key demo'),
        centerTitle: true,
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: items,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            items.removeAt(0);
          });
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

class StfulItem extends StatefulWidget {
  final String title;

  StfulItem({super.key, required this.title});

  @override
  State<StfulItem> createState() => _StfulItemState();
}

class _StfulItemState extends State<StfulItem> {
  final color = Color.fromRGBO(
      Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1.0);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100,
      height: 100,
      child: Text(widget.title),
      color: color,
    );
  }
}

class StlItem extends StatelessWidget {
  StlItem({super.key, required this.title});

  final String title;
  final color = Color.fromRGBO(
      Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1.0);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100,
      height: 100,
      child: Text(title),

      color: color,
    );
  }
}
